package com.meals.system.service.impl;

import com.meals.system.api.system.vo.WhitesMealIndexCarouselVO;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.dao.CarouselMapper;
import com.meals.system.entity.Carousel;
import com.meals.system.service.WhitesMealCarouselService;
import com.meals.system.util.BeanUtil;
import com.meals.system.util.PageQueryUtil;
import com.meals.system.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/4
 */
@Service
public class WhitesMealCarouselServiceImpl implements WhitesMealCarouselService {

    @Autowired
    private CarouselMapper carouselMapper;

    @Override
    public List<WhitesMealIndexCarouselVO> getCarouselsForIndex(int number){
        List<WhitesMealIndexCarouselVO> whitesMealIndexCarouselVOS = new ArrayList<>(number);
        List<Carousel> carousels = carouselMapper.findCarouselsByNum(number);
        if (!CollectionUtils.isEmpty(carousels)){
            whitesMealIndexCarouselVOS = BeanUtil.copyList(carousels, WhitesMealIndexCarouselVO.class);
        }
        return whitesMealIndexCarouselVOS;
    }

    /**
     * 后台
     */
    @Override
    public PageResult getCarouselPage(PageQueryUtil pageUtil){
        List<Carousel> carousels = carouselMapper.findCarouselList(pageUtil);
        int total = carouselMapper.getTotalCarousels(pageUtil);
        PageResult pageResult = new PageResult(carousels, total, pageUtil.getLimit(),pageUtil.getPage());
        return pageResult;
    }

    @Override
    public String saveCarousel(Carousel carousel){
        if (carouselMapper.insertSelective(carousel) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateCarousel(Carousel carousel){
        Carousel temp = carouselMapper.selectByPrimaryKey(carousel.getCarouselId());
        if (temp == null){
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        temp.setCarouselRank(carousel.getCarouselRank());
        temp.setCarouselUrl(carousel.getCarouselUrl());
        temp.setRedirectUrl(carousel.getRedirectUrl());
        temp.setUpdateTime(new Date());
        if (carouselMapper.updateByPrimaryKeySelective(temp) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public Carousel getCarouselById(Integer id){
        return carouselMapper.selectByPrimaryKey(id);
    }


    @Override
    public Boolean deleteBatch(Long[] ids){
        if (ids.length < 1){
            return false;
        }
        // 删除数据
        return carouselMapper.deleteBatch(ids) > 0;
    }
}
